package cn.swu.ws;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.Writer;
import java.util.Enumeration;

public class LoginServlet extends HttpServlet {
    public void init(ServletConfig config){
        System.out.println("login的类已经开始运行");
    }
    public void  destory(){
        System.out.println("login的类运行结束");
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name=request.getParameter("user");
        String password=request.getParameter("password");
        response.setContentType("text/html");
        HttpSession session = request.getSession(true);
        Writer webWriter=response.getWriter();
        //下面全是打印信息的验证
        Enumeration<String> nameHeader=request.getParameterNames();
        System.out.println(name);
        System.out.println(password);;
        while (nameHeader.hasMoreElements()){
            System.out.println(nameHeader.nextElement());
        }
        if(name.equals("admin") && password.equals("123456")){
            response.sendRedirect("./main");
            session.setAttribute("loginState", LoginState.LOGIN_SUCCESS);
            return;
        }
        webWriter.write("<html><head><title>login</title></head><body> <center><h1>登陆失败！！！</h1></center></body></html>");
        //response.sendRedirect("./index.html");
        session.setAttribute("loginState", LoginState.LOGIN_FAILED);
        response.setHeader("refresh", "3;url=./index.html");

    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request,response);
    }
}
